<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\analysis\account;

use app\command\BaseWork;
use app\model\mongo\MongoClientMediaMonthStatModel;
use app\service\analysis\data\account\ClientMonthStatService;
use think\console\Input;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class ClientMonthStatWork extends BaseWork
{
    protected function configure()
    {
        // 指令配置
        $this->setName('analysis_client_month_stat_work');
        // 设置参数
        $this->setDescription('数据分析-客户月汇总')
            ->setHelp('php think analysis_client_month_stat_work');
    }

    /**
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);

        $obj = new ClientMonthStatService();
        $t = time();
        $runTime = 5 * 60;
        while (time() - $t <= $runTime) {
            $list = $obj->getList();
            if (! count($list)) {
                sleep(rand(5, 10));
                $this->getOutputMessage('暂无数据');
                continue;
            }
            foreach ($list as $model) {
                if (! $model instanceof MongoClientMediaMonthStatModel || ! $model->getKey()) {
                    continue;
                }
                try {
                    $this->getOutputMessage('汇总[' . $model->getKey() . ']开始');
                    if (! $obj->runTask($model)) {
                        $this->getOutputMessage('汇总[' . $model->getKey() . ']失败:' . $obj::getError(0));
                    }
                    $this->getOutputMessage('汇总[' . $model->getKey() . ']完成');
                } catch (\Exception $e) {
                    $this->getOutputMessage('错误：' . $e->getMessage());
                    echo $e->getLine() . PHP_EOL;
                    echo $e->getFile() . PHP_EOL;
                    echo $e->getTraceAsString() . PHP_EOL;
                }
            }
        }
        $this->getOutputMessage('客户月汇总结束');
    }
}
